import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as productAction from '../store/actions/product.action'
import * as cartAction from '../store/actions/cart.actions'

class Product extends Component {
  componentDidMount() {
    const { loadProducts } = this.props
    loadProducts()
  }
  render() {
    const { list, addProductToCart } = this.props
    return (
      <section className="container content-section">
        <h2 className="section-header">商品列表</h2>
        <div className="shop-items">
          {list.map((item, index) => (
            <div className="shop-item" key={index}>
              <img alt="" className="shop-item-image" src={window.BASE_URL + item.thumbnail} />
              <span className="shop-item-title">{item.title}</span>
              <div className="shop-item-details">
                <span className="shop-item-price">￥{item.price}</span>
                <button 
                  className="btn btn-primary shop-item-button" 
                  type="button"
                  onClick={() => addProductToCart(item.id)}
                >
                  加入购物车
                </button>
              </div>
            </div>
          ))}
        </div>
      </section>
    )
  }
}

const mapStateToProps = state => ({
  list: state.products.list
})

const mapDispatchToProps = dispatch => ({
  ...bindActionCreators(productAction, dispatch),
  ...bindActionCreators(cartAction, dispatch)
})
/**
 * connect
 * 获取 store 中的某个值
 * mapStateToProps 映射函数
 * mapDispatchToProps 将 Action 映射到props中
 */
export default connect(mapStateToProps, mapDispatchToProps)(Product)
